/**
 * 
 */
package org.ucn.dmaa0914.gruppe6;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Kim Johannsen
 * @version 02-02-2015 
 */
public class OrderCtr extends CrudController<Order> {
	private static OrderCtr instance;
	private int currentOrder;
	
	public static OrderCtr getInstance()
	{
		if( instance == null )
			instance = new OrderCtr();
		
		return instance;
	}
	
	/**
	 * 
	 * @param id
	 * @param barcode
	 * @param amount
	 */
	public void addPartOrder(int orderId, int itemId, int amount)
	{
		Item item = ItemCtr.getInstance().find(itemId);
		Order order = find(orderId);
		
		if( item != null && order != null )
		{
			for( PartOrder po : order.getPartOrders() )
			{
				if( po.getItem().getId() == itemId )
				{
					po.setAmount(po.getAmount() + amount);
					return;
				}
			}
			
			PartOrder po = new PartOrder(item, amount);
			order.getPartOrders().add(po);
		}
	}
	
	public void removePartOrder(int orderId, int itemId, int amount)
	{
		Order order = find(orderId);
		
		for( PartOrder po : order.getPartOrders() )
		{
			if( po.getItem().getId() == itemId )
			{
				po.setAmount(po.getAmount() - amount);
				if( po.getAmount() <= 0 )
				{
					order.getPartOrders().remove(po);
				}
				return;
			}
		}
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	public boolean endOrder(int orderId)
	{
		Employee e = EmployeeCtr.getInstance().find(EmployeeCtr.getInstance().getCurrentEmployee());
		Order o = find(orderId);
		
		if( e == null || o == null )
			return false;
		
		
		o.setEmployee(e.getId());
		o.setPaid(true);
		
		return true; //TODO: Payment service lacking
	}
	
	public void updateOrder(int orderId, int customerId, int employeeId, Date date)
	{
		Customer c = CustomerCtr.getInstance().find(customerId);
		Employee e = EmployeeCtr.getInstance().find(employeeId);
		
		Order o = find(orderId);
		
		if( e != null )
			o.setEmployee(e.getId());
		
		if( c != null )
			o.setCustomer(c.getId());
		
		if( date != null )
			o.setDate(date);
	}
	
	public double getSubTotal(int orderId, int partOrderIndex)
	{
		Order o = find(orderId);
		PartOrder po = o.getPartOrders().get(partOrderIndex);
		return po.getAmount() * po.getItem().getPrice();
	}

	@Override
	protected SearchFilter<Order> getSearchFilter() {
		return new OrderSearchFilter();
	}

	@Override
	protected Order newObject() {
		return new Order();
	}

	public void setCurrentOrder(int selectedValue) {
		currentOrder = selectedValue;
	}

	public int getCurrentOrder() {
		return currentOrder;
	}

	@Override
	public String format(int id) {
		DateFormat df = new SimpleDateFormat();
		return String.format("#%d : %s", find(id).getId(), df.format(find(id).getDate()));
	}
}
